package cn.rkylin.oms.base.brand.service;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.apollo.common.util.SnoGerUtil;
import cn.rkylin.oms.base.brand.response.BrandRecord;
import cn.rkylin.oms.base.brand.response.DownLoadBrandResponse;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.base.brand.dao.IBrandDAO;
import cn.rkylin.oms.base.brand.domain.Brand;
import cn.rkylin.oms.base.brand.vo.BrandVO;

import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名：BrandServiceServiceImpl<br>
 * 作用：品牌信息服务层<br>
 * 创建时间：2018年1月24日 下午2:42:18
 *
 * @author LiPeng
 */
@Service
public class BrandServiceImpl extends ApolloService implements IBrandService {

    @Value("${mdm.server.url}")
    private String mdmServerUrl;

    @Value("${mdm.server.security}")
    private String mdmServerSecurity;

    @Value("${mdm.server.appId}")
    private String mdmServerAppId;

    /**
     * brandDAO：品牌信息数据层
     */
    @Autowired
    private IBrandDAO brandDAO;

    /**
     * 查询品牌信息列表
     */
    @Override
    public PageInfo<BrandVO> queryBrandList(int page, int length, BrandVO queryParamVO) throws Exception {
        return brandDAO.queryBrandList(page, length, queryParamVO);
    }

    /**
     * 品牌下载
     *
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> downLoadBrand() throws Exception {

        return downLoadBrand(1, 1);
    }

    /**
     * 品牌下载
     *
     * @param pageIndex
     * @param rows
     * @return
     * @throws Exception
     */
    private Map<String, Object> downLoadBrand(int pageIndex, int rows) throws Exception {

        Map<String, Object> rMap = new HashMap<>();
        String data = "{\"system_code\":\"ERP001\",\"page\":" + pageIndex + ",\"page_size\":\"1000\"}";
        String t = String.valueOf((new Date()).getTime());
        String sign = MD5(mdmServerSecurity + t + data);
        StringBuffer sb = new StringBuffer();
        sb.append(mdmServerUrl + "/api/mdm_brand_template_instance/query" + "?");
        sb.append("appId=" + mdmServerAppId);
        sb.append("&timestamp=" + t);
        sb.append("&sign=" + sign);
        sb.append("&system_code=ERP001&page=" + pageIndex + "&page_size=1000");
//        sb.append("&data=" + data);

        String json = HttpUtils.sendByPost(sb.toString(),data);//HttpUtils.sendByGet(sb.toString(), null);
        if (StringUtils.isBlank(json)) {
            rMap.put("success", "n");
            rMap.put("msg", "response json is null");
            return rMap;
        }
        System.out.println(json);

        DownLoadBrandResponse downLoadBrandResponse = JSON.parseObject(json, DownLoadBrandResponse.class);
        List<BrandRecord> lstBrandRecords = downLoadBrandResponse.getResult().getData().getRecords();
        for (BrandRecord brandRecord : lstBrandRecords) {

            BrandVO brandVO = new BrandVO();
            brandVO.setMdmCode(brandRecord.getMdm_code());
            brandVO.setBrandCode(brandRecord.getBrand_code());
            brandVO.setBrandName(brandRecord.getBrand_name());
            brandVO.setRemark(brandRecord.getRemark());
            brandVO.setEntId("51f17f6ddbae11e68c4d001e67c7ec3a");
            brandVO.setEntName("瑞金麟集团");

            // 打补丁, 对接方接口中包含脏数据, 没办法
            if (brandRecord.getBrand_code() == null) {
                continue;
            }

            BrandVO brandVOSelect = brandDAO.selectByMdmCodeBrand(brandVO.getMdmCode());
            if (brandVOSelect == null) {
                brandVO.setBrandId(SnoGerUtil.getUUID());
                brandDAO.insert(brandVO);
            } else {
                brandVO.setBrandId(brandVOSelect.getBrandId());
                brandDAO.updateByMdmCodeSelectiveBrand(brandVO);
            }
        }

        rMap.put("success", "y");
        rMap.put("msg", "");
        return rMap;
    }

    /**
     * 品牌反馈通知
     *
     * @param json
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> receiveBrand(String json, String type) throws Exception {

        Map<String, Object> rMap = new HashMap<>();

        List<BrandRecord> lstBrandRecords = JSON.parseArray(json, BrandRecord.class);
        if (lstBrandRecords == null || lstBrandRecords.size() == 0) {
            rMap.put("status", "S4");
            rMap.put("message", "lstBrandRecords is null");
            return rMap;
        }

        for (BrandRecord brandRecord : lstBrandRecords) {

            BrandVO brandVO = new BrandVO();
            brandVO.setMdmCode(brandRecord.getMdm_code());
            brandVO.setBrandCode(brandRecord.getBrand_code());
            brandVO.setBrandName(brandRecord.getBrand_name());
            brandVO.setRemark(brandRecord.getRemark());
            brandVO.setEntId("51f17f6ddbae11e68c4d001e67c7ec3a");
            brandVO.setEntName("瑞金麟集团");
            //暂时不要对应删除
//            if ("3".equals(type)) {
//                brandVO.setDeleted("y");
//            } else {
//                brandVO.setDeleted("n");
//            }

            // 打补丁, 对接方接口中包含脏数据, 没办法
            if (brandRecord.getBrand_code() == null) {
                continue;
            }

            BrandVO brandVOSelect = brandDAO.selectByMdmCodeBrand(brandVO.getMdmCode());
            if (brandVOSelect == null) {
                brandVO.setBrandId(SnoGerUtil.getUUID());
                brandDAO.insert(brandVO);
            } else {
                brandVO.setBrandId(brandVOSelect.getBrandId());
                brandDAO.updateByMdmCodeSelectiveBrand(brandVO);
            }
        }

        rMap.put("status", "S1");
        rMap.put("message", "成功！");
        rMap.put("data",lstBrandRecords);
        return rMap;
    }


    private static String MD5(String message) {
        String mess = message;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = mess.getBytes("UTF-8");
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取品牌信息
     * @param id
     * @return
     * @throws Exception
     */
	@Override
	public BrandVO getBrandById(String id) throws Exception {
		BrandVO brandVO = brandDAO.findById(id);
        return brandVO;
	}

	 /**
     * 获取code
     * 
     * @param id
     * @return
     * @throws Exception
     */
	@Override
    public BrandVO getBrandByBrandCode(BrandVO brandVO) throws Exception{
		return brandDAO.selectByBrandCode(brandVO);
	}
	
    /**
     * 创建品牌信息
     * @param brandVO
     * @return
     * @throws Exception
     */
	@Override
	public Brand insert(BrandVO brandVO) throws Exception {
		Brand brand = new Brand();
        BeanUtils.copyProperties(brandVO, brand);
        brandDAO.insert(brand);
        return brand;
	}
	
    /**
     * 修改品牌信息
     * @param brandVO
     * @return
     * @throws Exception
     */
	@Override
    public Brand update(BrandVO brandVO) throws Exception{
		Brand brand = new Brand();
        BeanUtils.copyProperties(brandVO, brand);
        brandDAO.update(brand);
        return brand;
    }
    
    /**
     * 删除品牌信息
     * @param brandID
     * @return
     * @throws Exception
     */
	@Override
	public int delete(String brandID) throws Exception {
		return brandDAO.delete(brandID);
	}
}
